package com.tang.common.utils;

import com.alibaba.fastjson.JSON;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ExtendedServletRequestDataBinder;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author tang jun liang
 * @Date 2023/5/20 16:46
 */
public class CoolUtil {


    public static String getRequestParam(String[] parameterNames, Object[] args) {
        Map<String, String> map = new LinkedHashMap<>();
        for (int i = 0; i < parameterNames.length; i++) {
            if (args[i] instanceof HttpServletResponse) {
                continue;
            }
            if (args[i] instanceof HttpServletRequest) {
                continue;
            }
            if (args[i] instanceof ExtendedServletRequestDataBinder) {
                continue;
            }
            if (args[i] instanceof BindingResult) {
                continue;
            }
            if (args[i] instanceof MultipartFile) {
                continue;
            }
            if (args[i] instanceof HttpSession) {
                continue;
            }
            if (args[i] instanceof Model) {
                continue;
            }
            if (args[i] instanceof ModelAndView) {
                continue;
            }
            map.put(parameterNames[i], JSON.toJSONString(args[i]));
        }
        return JSON.toJSONString(map);
    }


    public static int getStringNum(String value, String object) {
        String newValue = value.replaceAll(object, "");
        return (value.length() - newValue.length()) / object.length();
    }


    /**
     * 获取在指定数组的锁引
     *
     * @param arrays
     * @return
     * @apiNote
     */
    public static int getIndex(String[] arrays, String object) {
        for (int i = 0; i < arrays.length; i++) {
            if (arrays[i].equals(object)) {
                return i;
            }
        }
        return -1;
    }

    public static String camelToUnderline(String str) {
        if (str == null || "".equals(str.trim())) {
            return "";
        }
        int len = str.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = str.charAt(i);
            if (Character.isUpperCase(c)) {
                if (i == 0) {
                    sb.append(Character.toLowerCase(c));
                    continue;
                }
                sb.append("_").append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

}
